from datetime import datetime
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
from reportlab.lib.styles import getSampleStyleSheet
import logging

logger = logging.getLogger(__name__)

class ReportGenerator:
    """PDF报告生成器"""
    
    def __init__(self, output_path="tech_trend_report.pdf"):
        self.output_path = output_path
        self.styles = getSampleStyleSheet()
        
    def generate_report(self, analysis_results):
        """生成PDF报告
        
        Args:
            analysis_results: analyze_trends()返回的分析结果
        """
        try:
            doc = SimpleDocTemplate(
                self.output_path,
                pagesize=letter,
                rightMargin=72,
                leftMargin=72,
                topMargin=72,
                bottomMargin=18
            )
            
            story = []
            
            # 添加标题
            title = Paragraph("科技趋势分析报告", self.styles["Title"])
            story.append(title)
            story.append(Spacer(1, 12))
            
            # 添加日期
            date_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            date_text = Paragraph(f"生成时间: {date_str}", self.styles["Normal"])
            story.append(date_text)
            story.append(Spacer(1, 24))
            
            # 添加分析结果
            analysis_text = analysis_results['trend_analysis'].replace("\n", "<br/>")
            analysis_para = Paragraph(analysis_text, self.styles["Normal"])
            story.append(analysis_para)
            story.append(Spacer(1, 24))
            
            # 添加可视化图表
            chart = Image("tech_trends.png", width=400, height=300)
            story.append(chart)
            
            doc.build(story)
            logger.info(f"PDF报告已生成: {self.output_path}")
            return True
            
        except Exception as e:
            logger.error(f"生成PDF报告失败: {str(e)}")
            return False